<!-- 工具管理-工具盘点页面 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="工具盘点名称/编码">
              <px-input
                v-model="queryParams.takeNameOrCode"
                placeholder="请输入工具盘点名称/编码"
                maxlength="50"
                clearable
                @blur="queryParams.takeNameOrCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="所属计划编码">
              <px-input
                v-model="queryParams.takePlanCode"
                placeholder="请输入所属计划编码"
                maxlength="50"
                clearable
                @blur="queryParams.takePlanCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6" class="form-date-class">
            <px-form-item label="日期" prop="planStartDate" style="width: 52%">
              <px-date-picker
                v-model="queryParams.planStartDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="开始日期"
                @change="changePlanStartDate"
              />
            </px-form-item>
            <span>-</span>
            <px-form-item label="" prop="planEndDate" style="width: calc(48% - 20px)">
              <px-date-picker
                v-model="queryParams.planEndDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="结束日期"
                @change="changePlanEndDate"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="执行状态">
              <px-select v-model="queryParams.executeStatus" placeholder="请选择执行状态" filterable clearable>
                <px-option v-for="(item, index) in executeStatusList" :key="index" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="4">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_ADD'" type="primary" style="margin-right: 8px" @click="addToolInventory">新增</px-button>
        <!-- <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_GROUP'" style="margin-left: 8px" plain type="primary" @click="linkToGroup">
          盘点组管理
        </px-button> -->
        <!-- 2.3.0再实现这个功能 -->
        <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_REPORT'" :disabled="selectIds.length === 0" plain type="primary" @click="handleDownload">
          生成盘点报告
        </px-button>
      </div>
      <px-table :data="tableData" class="equip-table" height="calc(100vh - 360px)" border @selection-change="handleSelectionChange">
        <px-table-column type="selection" :selectable="handleCanSelect" width="50" align="center" />
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template v-if="item.type === 'taskCode'" #default="scope">
            <span
              v-if="isHasPermission('ALL_EQUIP_TOOLMANAGE_INVENTORY_VIEW')"
              style="color: #3b82f6; cursor: pointer"
              @click="handleView(scope.row)"
            >
              {{ scope.row.takeStockCode }}
            </span>
            <span v-else>{{ scope.row.takeStockCode }}</span>
          </template>
          <template v-else-if="item.type === 'status'" #default="scope">
            <div class="status">
              <div class="circle" :style="{ backgroundColor: `${tagBgColorList[scope.row.executeStatus]}` }" />
              <p :style="{ color: `${tagBgColorList[scope.row.executeStatus]}` }">{{ scope.row.executeStatusDesc }}</p>
            </div>
          </template>
          <template v-else #default="scope">{{
            scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
          }}</template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" min-width="150" align="center">
          <template #default="scope">
            <!-- 盘点报告 -->
            <px-tooltip v-if="[3, 5].includes(scope.row.executeStatus)" content="盘点报告" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_REPORT'" link type="primary" icon="Report" @click="handleReport(scope.row)" />
            </px-tooltip>
            <!-- 盘点 -->
            <px-tooltip v-if="(scope.row.executeStatus === 1 && scope.row.isTake) || scope.row.executeStatus === 2" content="盘点" placement="top">
              <px-button
                v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_INVENTORY'"
                link
                type="primary"
                icon="BasicRecords"
                @click="handleInventory(scope.row)"
              />
            </px-tooltip>
            <!-- 详情 -->
            <px-tooltip
              v-if="scope.row.executeStatus === 0 || scope.row.executeStatus === 1 || scope.row.executeStatus === 2 || scope.row.executeStatus === 4"
              content="详情"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <!-- 编辑 -->
            <px-tooltip v-if="scope.row.executeStatus === 0 || scope.row.executeStatus === 1" content="编辑" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <!-- 删除 -->
            <px-tooltip v-if="scope.row.executeStatus === 0 || scope.row.executeStatus === 1" content="删除" placement="top">
              <px-button v-has="'ALL_EQUIP_TOOLMANAGE_INVENTORY_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddSparePartsDetail
      :isMain="isMain"
      :isView="isView"
      :isDraftVisible="isDraftVisible"
      :drawerType="drawerType"
      :inventoryId="inventoryId"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 详情查看页面 -->
    <ViewSparePartsDetail
      :isMain="isMain"
      :isView="isView"
      :isInventory="isInventory"
      :inventoryId="inventoryId"
      @queryTable="queryTable"
      @backMainPage="backMainPage"
    />
    <!-- 盘点报告页面 -->
    <ViewSparePartsReport :visible="visible" :inventoryId="inventoryId" @closeDialog="closeDialog" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_TOOLMANAGE_INVENTORY"
});

import { delToolInventory, queryToolInventory } from "@/api/equip/toolManage";
import { isHasPermission } from "@/utils/auth";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, toRefs } from "vue";
import AddSparePartsDetail from "./components/AddSparePartsDetail.vue";
import ViewSparePartsDetail from "./components/ViewSparePartsDetail.vue";
import ViewSparePartsReport from "./components/ViewSparePartsReport.vue";

const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  isInventory: false, // 盘点true，查看false
  executeStatusList: [
    { name: "全部", value: "" },
    { name: "未开始", value: 1 },
    { name: "执行中", value: 2 },
    { name: "已完成", value: 3 },
    { name: "已完成（超期）", value: 5 },
    { name: "草稿", value: 0 }
  ],
  queryParams: {
    takeNameOrCode: "",
    takePlanCode: "",
    className: "",
    planStartDate: "",
    planEndDate: "",
    executeStatus: "",
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "takeStockName", label: "工具盘点名称", minWidth: "160", showOverflowTooltip: true },
    { prop: "takeStockCode", label: "工具盘点编码", minWidth: "160", type: "taskCode", showOverflowTooltip: true },
    // { prop: "takePlanCode", label: "盘点计划名称", minWidth: "160", showOverflowTooltip: true },
    { prop: "takePlanCode", label: "所属计划编码", minWidth: "160", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "80", showOverflowTooltip: true },
    { prop: "planDate", label: "任务计划时间", minWidth: "180", showOverflowTooltip: true },
    { prop: "takeStockPeopleName", label: "盘点负责人", minWidth: "120", showOverflowTooltip: true },
    { prop: "executeStatus", label: "执行状态", minWidth: "100", showOverflowTooltip: true, type: "status" },
    { prop: "executeTime", label: "执行时间", minWidth: "140", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  drawerType: "add",
  inventoryId: "",
  visible: false,
  isDraftVisible: true,
  selectIds: []
});
const {
  isMain,
  isView,
  isInventory,
  executeStatusList,
  queryParams,
  tableColumns,
  tableData,
  total,
  drawerType,
  inventoryId,
  visible,
  isDraftVisible,
  selectIds
} = toRefs(state);

// 多选时该行是否可以选中
const handleCanSelect = row => {
  return row.executeStatus === 3 || row.executeStatus === 5;
};

/** 多选框选中数据 */
const handleSelectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
};

const { proxy } = getCurrentInstance();

// 批量下载
const handleDownload = async () => {
  proxy.download("post", `/digitaltwins/api/v1/toolTakeStock/exportToolTakeStockReport`, { ids: selectIds.value }, "盘点报告下载.xlsx");
};

const tagBgColorList = {
  0: "#dedfe0", // 草稿
  1: "#f59e0b", // 未开始
  2: "#3b82f6", // 执行中
  3: "#10b981", // 已完成
  5: "#10b981" // 已完成(超期)
};

const route = useRoute();
// 进入页面时触发
onMounted(() => {
  const { code, type, inventoryId: id } = route.query;
  if (type === "view") {
    inventoryId.value = id;
    isMain.value = false;
    isView.value = true;
    isInventory.value = false;
  } else if (type === "list") {
    queryParams.value.takePlanCode = code;
  } else if (type === "report") {
    queryParams.value.takeNameOrCode = code;
  }
  queryTable();
});
// 获取计划日期开始
const changePlanStartDate = () => {
  if (queryParams.value.planStartDate && queryParams.value.planEndDate) {
    if (queryParams.value.planStartDate > queryParams.value.planEndDate) {
      queryParams.value.planEndDate = queryParams.value.planStartDate;
    }
  }
};
// 获取计划日期结束
const changePlanEndDate = () => {
  if (queryParams.value.planStartDate && queryParams.value.planEndDate) {
    if (queryParams.value.planStartDate > queryParams.value.planEndDate) {
      queryParams.value.planStartDate = queryParams.value.planEndDate;
    }
  }
};
// 查询工具列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  if (!queryParams.value.planStartDate && !queryParams.value.planEndDate) {
    delete params.planStartDate;
    delete params.planEndDate;
  } else if (!queryParams.value.planStartDate && queryParams.value.planEndDate) {
    delete params.planStartDate;
  } else if (queryParams.value.planStartDate && !queryParams.value.planEndDate) {
    delete params.planEndDate;
  }
  const data = await queryToolInventory(params);
  data?.data.forEach(item => {
    item.planDate = item.planStartDate + " - " + item.planEndDate;
  });
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件和工具列表
const resetTable = async () => {
  queryParams.value = {
    takeNameOrCode: "",
    takePlanCode: "",
    className: "",
    planStartDate: "",
    planEndDate: "",
    executeStatus: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
// 盘点报告工具详情
const handleReport = (row: any) => {
  inventoryId.value = row.id;
  visible.value = true;
};
// 盘点工具详情
const handleInventory = (row: any) => {
  inventoryId.value = row.id;
  isMain.value = false;
  isView.value = true;
  isInventory.value = true;
};
// 查看盘点工具详情
const handleView = (row: any) => {
  inventoryId.value = row.id;
  isMain.value = false;
  isView.value = true;
  isInventory.value = false;
};
// 添加盘点工具详情
const addToolInventory = () => {
  drawerType.value = "add";
  isMain.value = false;
  isView.value = false;
  isDraftVisible.value = true;
};

import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const linkToGroup = () => {
  router.push("/all/equip/toolManage/toolGroup");
};

// 编辑盘点工具详情
const handleEdit = (row: any) => {
  drawerType.value = "edit";
  inventoryId.value = row.id;
  isMain.value = false;
  isView.value = false;
  isDraftVisible.value = row.executeStatus === 1 ? false : true;
};
// 删除工具盘点
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前工具盘点“${row.takeStockName}”吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delToolInventory(row.id);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
};
// 从盘点报告返回主页面
const closeDialog = () => {
  visible.value = false;
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.form-date-class {
  display: flex;

  .px-form-item {
    margin-right: 0;
  }

  :deep(.px-form-item__content) {
    margin-left: 0 !important;

    .px-input__wrapper {
      border-radius: 4px;
    }
  }

  span {
    width: 20px;
    margin-top: 5px;
    text-align: center;
  }
}

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
